<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/10/7 Time: 14:44
 */

namespace App\Repositories\Order;

use App\Lib\Utils\Cart;
use App\Lib\Utils\OrderFilter;
use App\Models\Order\Order;
use App\Models\Product\OrderItem;
use App\Repositories\Repository;
use Illuminate\Support\Facades\DB;

class OrderRepository extends Repository
{
    public function orders($params)
    {

    }

    public function show($order_number)
    {
        //订单数据

        //订单促销活动

        //订单商品

        //商品优惠信息
    }


    public function post($cart_keys)
    {
        //获取购物车勾选的产品
        $items = Cart::getCar()->listItems();
        if (!$cart_keys) {
            return $this->respondError(10605);
        }

        $products = [];
        foreach ($cart_keys as $cart_key) {
            if (!isset($items[$cart_key])) {
                return $this->respondError(10605);
            }
            $products[] = $items[$cart_key];
        }

        //计算价格

    }

    public function addOrder($data)
    {

        //生成订单号
        $order_number = $this->createOrderNumber();
        if (!$order_number) {
            return $this->respondError(10600);
        }

    }

    public function saveOrder($order_number)
    {

    }




    /*=========================================================================================
        私有方法
    ==========================================================================================*/

    private function createOrderNumber()
    {
        //组装键名
        $key = 'orders_' . date('Ymd');

        if (!app('phpredis')->exists($key)) {
            //并发情况下，不是第一个进入的返回空值
            if (app('phpredis')->exists("tem" . $key)) {
                return false;
            }
            app('phpredis')->setex("tem" . $key, 5, 1);
            $number = $this->getNumber();
            app('phpredis')->setex($key, 86400, $number);
            app('phpredis')->del("tem" . $key);
        }
        $number = app('phpredis')->incr($key);
        return date('ymd') . rand(10, 99) . $number . rand(0, 9);
    }


    private function getNumber()
    {
        $rs = 0;
        $number = Order::query()->orderBy("created_at", "desc")->value('order_number');
        if ($number) {
            $day = substr($number, 0, 8);
            if ($day == date('Ymd')) {
                //删除随机的2位数字
                $tmp_number = substr($number, 0, strlen($number) - 1);
                $rs = (int)substr($tmp_number, 9);
            }
        }
        return $rs;
    }


}